﻿/* Code based on RoundButton from http://coding4fun.codeplex.com/ */
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Imaging;

namespace DanielVaughan.Windows.Controls
{
	[TemplatePart(Name = OpacityImageBrushName, Type = typeof(ImageBrush))]
	public class RoundButton : Button
	{
		protected ImageBrush OpacityImageBrush;
		const string OpacityImageBrushName = "OpacityImageBrush";

		public RoundButton()
		{
			DefaultStyleKey = typeof(RoundButton);
		}

		public override void OnApplyTemplate()
		{
			base.OnApplyTemplate();

			OpacityImageBrush = (ImageBrush)GetTemplateChild(OpacityImageBrushName);

			if (OpacityImageBrush != null && ImageSource != null)
			{
				OpacityImageBrush.ImageSource = ImageSource;
			}
		}

		public static readonly DependencyProperty ImageSourceProperty
			= DependencyProperty.Register(
				"ImageSource",
				typeof(ImageSource),
				typeof(RoundButton),
				new PropertyMetadata(
					new BitmapImage(
						new Uri("/Calcium.Phone;component/Windows/Controls/RoundButton/Images/CheckMark.png",
								UriKind.Relative)), HandleImageSourceChanged));

		static void HandleImageSourceChanged(
			DependencyObject d, DependencyPropertyChangedEventArgs e)
		{
			var roundButton = d as RoundButton;

			if (roundButton == null || roundButton.OpacityImageBrush == null)
			{
				return;
			}

			var imageSource = (ImageSource)e.NewValue;
			roundButton.OpacityImageBrush.ImageSource = imageSource;
		}

		public ImageSource ImageSource
		{
			get
			{
				return (ImageSource)GetValue(ImageSourceProperty);
			}
			set
			{
				SetValue(ImageSourceProperty, value);
			}
		}
	}
}
